package wsi.input;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.rygh.core.model.common.MapList;
import org.rygh.core.util.UIo;
import org.rygh.semantic.gui.swing.input.Input;
import org.rygh.semantic.model.rdf.Entity;
import org.rygh.semantic.model.rdf.Predicate;

import wsi.script.AppConfig;

public class SimpleCandidatePool {

	private final static SimpleCandidatePool shared = new SimpleCandidatePool();

	public final static SimpleCandidatePool shared() {
		return shared;
	}

	// we use list to preserve order.
	private final MapList<String, Input> inputMapList = new MapList<>();

	private SimpleCandidatePool() {

	}

	private String getKey(Entity type, Predicate namePredicate) {
		return String.format("%s_%s", type.getBodyString(),
				namePredicate.getBodyString());
	}

	public List<Input> load(Entity type, Predicate namePredicate) {
		String key = getKey(type, namePredicate);

		List<Input> inputs;

		if (inputMapList.containsKey(key))
			inputs = inputMapList.get(key);
		else {
			inputs = new LinkedList<>();
			inputMapList.put(key, inputs);

			// read for first load only
			read(inputs, key, namePredicate);
		}

		return inputs;
	}

	public void put(String key, Input input) {
		inputMapList.put(key, input);
	}

	private void read(List<Input> inputs, String key, Predicate namePredicate) {
		File dir = AppConfig.shared().getInputsFolder();
		File file = null;

		for (File f : dir.listFiles()) {
			if (f.isDirectory())
				continue;

			if (f.getName().startsWith(key)) {
				file = f;
				break;
			}
		}

		if (file == null)
			return;

		inputs.clear();

		JSONArray ja = new JSONArray(UIo.readFile(file));

		Input input;

		for (int i = 0; i < ja.length(); i++) {
			input = new Input(ja.getJSONArray(i));
			inputs.add(input);
		}
	}

	public void save(Entity type, Predicate namePredicate) {
		String key = getKey(type, namePredicate);

		List<Input> list = inputMapList.get(key);

		if (list == null)
			return;

		File dir = AppConfig.shared().getInputsFolder();
		File file = new File(dir, String.format("%s.txt", key));

		System.out.printf("save candidate size %d\n", list.size());

		JSONArray ja = new JSONArray();

		for (Input input : list)
			ja.put(input.getJsonArray());

		UIo.saveFile(file, ja.toString());
	}
}
